package edu.spec.chenli.Filter;

import com.sun.org.apache.xpath.internal.operations.String;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;

//@WebFilter(filterName = " log",urlPatterns = "/ts")
public class LoginFilter implements Filter {
   // private FilterConfig config;
    public LoginFilter(){
        System.out.println("logFilter的LogFilter()方法运行"+new Date());
    }
    public void init(FilterConfig filterConfig) throws ServletException {
        //this.config=config;
        System.out.println("logFilter的init()方法运行"+new Date());
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //System.out.println("logFilter的Filter()方法运行"+new Date());
       // java.lang.String encoding=config.getInitParameter("encoding");
       // servletRequest.setCharacterEncoding(encoding);
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpSession session = req.getSession(true);
        String username = (String)session.getAttribute("username");
        java.lang.String path = req.getServletPath();
        if("/sl".equals(path)){
            filterChain.doFilter(servletRequest, servletResponse);
            System.out.println("用户请求登录，时间：" + new Date());
        }else
            {
            if(username==null)
            {
                System.out.println("用户未登录，时间：" + new Date());
                req.getRequestDispatcher("login.jsp").forward(req, servletResponse);
            }else
                {
                filterChain.doFilter(servletRequest, servletResponse);
                System.out.println("用户已经登录，时间：" + new Date());
            }
        }
         //System.out.println("LoginFilter的doFilter()方法运行——req"+ new Date());
        //filterChain.doFilter(servletRequest,servletResponse);
       //System.out.println("LoginFilter的doFilter()方法运行——resp"+ new Date());
    }

    public void destroy() {
       // this.config=null;
        System.out.println("logFilter的destroy()方法运行"+new Date());
    }
}
